define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function ($, undefined, Backend, Table, Form, Vue) {

    var Controller = {
        index: function () {
            let cid = Config.cid;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'project/index' + location.search,
                    add_url: 'project/add/cid/'+cid,
                    edit_url: 'project/edit',
                    del_url: 'project/del',
                    multi_url: 'project/multi',
                    import_url: 'project/import',
                    table: 'project',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                showExport: false,
                showToggle: false,
                exportTypes : ['excel'],
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        // {field: 'category.name', operate: 'LIKE', title: __('Category_id')},
                        {field: 'remark', title: '标题'},
                        {field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'project/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'project/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'project/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.usevue();
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.usevue();
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },

            usevue: function (){
                new Vue({
                    el: "#vueBox",
                    data() {
                        return {
                            thead: [],
                            tbody: [],
                            lines: [],
                            state: [],
                            newVal: '',
                            newCol: '',
                            data_show: false
                        }
                    },
                    created(){

                        let title = $('#c-title').val();
                        if(title){
                            this.thead = title.split(',');
                        }

                        let content = $('#c-content').val();
                        if(content){
                            this.tbody = content.split('\n');
                        }

                        if(this.thead && this.tbody){
                            this.data_show = true;
                        }
                        this.make_data();
                    },
                    methods: {
                        postAndOpen(url, data, target) {
                            // 创建隐藏表单
                            var $form = $('<form>', {
                                method: 'post',
                                action: url,
                                target: target || '_self' // '_blank' 为新窗口，'_self' 为当前窗口
                            }).hide();

                            // 添加数据参数
                            $.each(data, function(key, value) {
                                $('<input>').attr({
                                    type: 'hidden',
                                    name: key,
                                    value: value
                                }).appendTo($form);
                            });

                            // 添加到DOM并提交
                            $('body').append($form);
                            $form.submit();
                        },

                        submit(){
                            let that = this;
                            let id = $('#id').val();
                            let category_id = $('#category_id').val();
                            Fast.api.ajax({
                                url: id?'project/edit/ids/'+id:'project/add',
                                loading: true,
                                type: "POST",
                                data: {
                                    row : {
                                        id : id,
                                        category_id : category_id,
                                        remark: $('#c-remark').val(),
                                        title: (that.thead).join(','),
                                        content: (that.tbody).join('\n')
                                    }
                                }
                            }, function (ret, res) {
                                Fast.api.close({
                                    data: true,
                                })
                                window.parent.$(".btn-refresh").trigger("click");
                            })
                        },
                        add_line(){
                            if(this.thead.includes(this.newVal)){
                                this.tbody.push(this.newVal);
                                this.newVal = '';
                                this.data_show = false;
                                this.make_data()
                            }else{
                                Layer.msg('请输入存在的值', {
                                    title: '提示',
                                    icon: 2 // 图标类型：0-警告，1-成功，2-错误，3-问号，4-锁定，5-哭脸，6-笑脸
                                });
                            }
                        },
                        add_col(){
                            if(!this.thead.includes(this.newCol)){
                                this.thead.push(this.newCol);
                                this.newCol = '';
                                this.data_show = false;
                                this.make_data()
                            }else{
                                Layer.msg('不能输入重复的值', {
                                    title: '提示',
                                    icon: 2 // 图标类型：0-警告，1-成功，2-错误，3-问号，4-锁定，5-哭脸，6-笑脸
                                });
                            }
                        },
                        line_change(e){
                            let idx = parseInt(e.target.dataset.idx);
                            let tbody = this.tbody;
                            if(e.target.value){
                                if(this.thead.includes(e.target.value)){
                                    tbody[idx] = e.target.value;
                                }else{
                                    Layer.msg('请输入存在的值', {
                                        title: '提示',
                                        icon: 2 // 图标类型：0-警告，1-成功，2-错误，3-问号，4-锁定，5-哭脸，6-笑脸
                                    });
                                }
                            }else{
                                tbody.splice(idx,1)
                            }
                            this.tbody = tbody;
                            this.data_show = false;
                            this.make_data()
                        },
                        col_change(e){
                            let idx = parseInt(e.target.dataset.idx);
                            let thead = this.thead;
                            if(e.target.value){
                                // if(!this.thead.includes(e.target.value)){
                                //     thead[idx] = e.target.value;
                                // }else{
                                //     Layer.msg('请不要输入重复的值', {
                                //         title: '提示',
                                //         icon: 2 // 图标类型：0-警告，1-成功，2-错误，3-问号，4-锁定，5-哭脸，6-笑脸
                                //     });
                                // }
                            }else{
                                thead.splice(idx,1)
                            }
                            this.thead = thead;
                            this.data_show = false;
                            this.make_data()
                        },
                        make_data(){
                            let sum = [];
                            for(let i=0;i<this.thead.length;i++){
                                sum.push(0);
                            }

                            let lines = [];
                            let line_pos;
                            this.state = [];
                            for(let t=0;t<this.tbody.length;t++){
                                line_pos = this.thead.indexOf(this.tbody[t]);
                                if(line_pos!==-1){
                                    sum[this.search_arr_key(line_pos-1)] += 1;
                                    sum[this.search_arr_key(line_pos-2)] += 1;
                                    sum[this.search_arr_key(line_pos)] += 1;
                                    sum[this.search_arr_key(line_pos+1)] += 1;
                                    sum[this.search_arr_key(line_pos+2)] += 1;

                                    if(this.checkDifference(sum)){
                                        //保证是双数行
                                        if((this.tbody.length-t) % 2 ===0){
                                            this.state.push(t);
                                        }
                                    }
                                    lines.push([...sum]);
                                }
                            }
                            this.lines = lines;
                        },
                        update_data(){
                            this.data_show = true;
                            this.make_data();
                        },
                        showAttach(idx){
                            let line_data = this.lines[idx];
                            // 获取最大值
                            let max = line_data.reduce((a, b) => a > b ? a : b);
                            // 获取最小值
                            let min = line_data.reduce((a, b) => a < b ? a : b);

                            let show_data = [];
                            let line_str = '';
                            for(min;min<=max;min++){
                                line_str = '';
                                for(let i=0;i<line_data.length;i++){
                                    if(line_data[i]===min){
                                        line_str += this.thead[i] + ',';
                                    }
                                }
                                show_data.push({
                                    num : min,
                                    str : line_str.replace(/,$/, '')
                                })
                            }


                            this.postAndOpen(Fast.api.fixurl('project/attach'), {
                                title: (this.thead).join(','),
                                sum: this.lines[idx],
                                remark: $('#c-remark').val(),
                                explain: '首('+ this.tbody[this.tbody.length-1] + ')'+this.tbody.length+'尾(' + this.tbody[idx] + ')' +(idx+1)+'得'+(this.tbody.length-idx),
                                content: JSON.stringify(show_data)
                            },'_blank');


                        },
                        //检查附表是否出现
                        checkDifference(arr) {
                            // 检查数组是否全是数字
                            if (arr.every(item => typeof item === 'number')) {
                                const max = Math.max(...arr);  // 最大值
                                const min = Math.min(...arr);  // 最小值
                                return max - min === 24;       // 如果最大数和最小数相差24，返回true
                            }
                            return false;  // 如果数组包含非数字元素，返回false
                        },
                        search_arr_key(key){
                            let length = this.thead.length;
                            if(key>=length){
                                return key-length;
                            }else if (key<0){
                                return key+length;
                            }else{
                                return key;
                            }
                        }
                    },
                });
            }
        }
    };
    return Controller;
});
